package com.kkb.mybatis.framework.builder;


import com.kkb.mybatis.framework.config.Configuration;
import com.kkb.mybatis.io.Resources;
import com.kkb.mybatis.utils.DocumentUtils;
import org.apache.commons.dbcp.BasicDataSource;
import org.dom4j.Document;
import org.dom4j.Element;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 *  该类用于解析全局配置文件
 */
public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parseConfiguration(Element rootElement) {

        Element environments = rootElement.element("environments");
        parseEnvironment(environments);

        Element mappers = rootElement.element("mappers");
        parseMappers(mappers);

    }

    private void parseEnvironment(Element environments) {
        String aDefault = environments.attributeValue("default");
        List<Element> elementList = environments.elements("environment");
        for (Element element : elementList) {
            String id = element.attributeValue("id");
            if (aDefault.equals(id)) {
                parseDataSource(element.element("dataSource"));
            }
        }
    }

    private void parseDataSource(Element dataSource) {
        String type = dataSource.attributeValue("type");
        // DBCP
        if (type.equals("DBCP")) {
            BasicDataSource basicDataSource = new BasicDataSource();
            Properties properties = parseProperties(dataSource);
            basicDataSource.setDriverClassName(properties.getProperty("db.driver"));
            basicDataSource.setUrl(properties.getProperty("db.url"));
            basicDataSource.setUsername(properties.getProperty("db.username"));
            basicDataSource.setPassword(properties.getProperty("db.password"));
            configuration.setDataSource(basicDataSource);
        }
        // 其他
    }

    private Properties parseProperties(Element element) {
        Properties properties = new Properties();
        List<Element> elementList = element.elements("property");
        for (Element property : elementList) {
            String name = property.attributeValue("name");
            String value = property.attributeValue("value");
            properties.setProperty(name, value);
        }
        return properties;
    }

    private void parseMappers(Element mappers) {
        List<Element> elementList = mappers.elements("mapper");
        for (Element element : elementList) {
            String resource = element.attributeValue("resource");
            InputStream inputStream = Resources.getResourceAsStream(resource);
            Document document = DocumentUtils.getDocument(inputStream);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parseMapper(document.getRootElement());
        }
    }
}
